/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;


import io.renren.common.utils.MyUtils;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.entity.dto.AppLoginDTO;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.service.UserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("app")
@Api(tags = "APP登录接口")
public class AppLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserTokenService userTokenService;

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestParam Map<Object,Object> map){
        AppLoginDTO form = new AppLoginDTO();
        MyUtils.copyMapToObject(map,form);
        //查询用户信息
        UserEntity user = userService.queryByUserPhone(form.getPhone());

        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(user.getStatus() == 0){
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = userTokenService.createToken(user.getId());
        return r;
    }

}
